package cn.conac.rc.gateway.modules.ofs.rest;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import cn.conac.rc.framework.utils.BeanMapper;
import cn.conac.rc.framework.utils.RestClientException;
import cn.conac.rc.framework.utils.ResultPojo;
import cn.conac.rc.gateway.modules.ofs.common.common;
import cn.conac.rc.gateway.modules.ofs.contsant.Contsants;
import cn.conac.rc.gateway.modules.ofs.entity.OrgOpinionsEntity;
import cn.conac.rc.gateway.modules.ofs.entity.OrgStatusEntity;
import cn.conac.rc.gateway.modules.ofs.entity.OrganizationEntity;
import cn.conac.rc.gateway.modules.ofs.service.OrgOpinionsService;
import cn.conac.rc.gateway.modules.ofs.service.OrgStatusService;
import cn.conac.rc.gateway.modules.ofs.service.OrganizationBaseService;
import cn.conac.rc.gateway.modules.ofs.service.OrganizationService;
import cn.conac.rc.gateway.security.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@RequestMapping(value = "ofs/")
@Api(tags = "部门审核信息", description = "三定信息")
public class OrgOpinionsController {
    
    @Autowired
    OrgOpinionsService orgOpinionsService;
    
    @Autowired
    OrgStatusService  orgStatusService;
    
    @Autowired
    OrganizationService  organizationService;
    
    @Autowired
    OrganizationBaseService organizationBaseService;
    
    @ApiOperation(value = "执行部门审核", httpMethod = "POST", response = JSONObject.class, notes = "执行部门审核")
    @RequestMapping(value = "opinions/{baseId}/audit", method = RequestMethod.POST)
    public Object cudOrgInfoAudit(HttpServletRequest request, HttpServletResponse response,
    		@ApiParam("部门基本信息Id") @PathVariable("baseId") Integer baseId,
            @ApiParam(value = "部门审核意见信息和状态信息的entity", required = true)  @RequestBody Map<String, Map<String, Object>> entityMap  )
            throws RestClientException, Exception {
    	
    	 ResultPojo resultInfo = new ResultPojo();
    	 if(null == baseId) {
    		  // 参数baseId为null场合
	       	  resultInfo.setCode(ResultPojo.CODE_FAILURE);
	          resultInfo.setMsg("[ baseId of parameter is null ] in function of orgInfoAudit " + ResultPojo.MSG_FAILURE);
	       	  resultInfo.setResult(null);
	       	  return resultInfo;
    	 }
    	 
    	 Map<String,String> idMap = new HashMap<String, String>();
    	 
    	//******************第一步从页面侧获取部门审核意见信息和部门状态实体对象***********
         // 获得基本信息
    	 OrgOpinionsEntity opinionsEntityInfo = new OrgOpinionsEntity();
    	 BeanMapper.copy(entityMap.get("opinionsEntity"), opinionsEntityInfo);
    	
    	 // 设置部门审核意见信息表baseId(确保Id不为null)
    	 opinionsEntityInfo.setBaseId(baseId.toString());
    	 if(StringUtils.isNotEmpty(UserUtils.getCurrentUser().getId())) {
    		 opinionsEntityInfo.setAuditUserId(Integer.valueOf(UserUtils.getCurrentUser().getId()));
 		 }
    	 
         // 获得部门状态信息
         OrgStatusEntity statusEntityInfo=  new OrgStatusEntity();
         BeanMapper.copy(entityMap.get("statusEntity"), statusEntityInfo);
         
         // 确保status不为null
         if(StringUtils.isEmpty(statusEntityInfo.getStatus())) {
   		  	  // 参数baseId为null场合
	       	  resultInfo.setCode(ResultPojo.CODE_FAILURE);
	          resultInfo.setMsg("[ status of parameter is null ] in function of orgInfoAudit " + ResultPojo.MSG_FAILURE);
	       	  resultInfo.setResult(null);
	       	  return resultInfo;
   	       }

         // 取得完整度掩码
         String stepMask = statusEntityInfo.getContentMask();
         // 审核阶段完整度掩码必须为【111111】
        if(!Contsants.OFS_FULL_CONTENT_MASK.equals(stepMask)) {
        	  // 完整度掩码不正场合
	       	  resultInfo.setCode(ResultPojo.CODE_FAILURE);
	          resultInfo.setMsg("[ The value of ContentMask is wrong (the value should be '111111') ] in function of orgInfoAudit " 
	        		  							+ ResultPojo.MSG_FAILURE);
	       	  resultInfo.setResult(null);
	       	  return resultInfo;
        }
         
         //******************第二步更新部门审核意见信息表**************************************
         // 执行保存部门审核意见信息表
    	 JSONObject opinionsInfoJson =  orgOpinionsService.saveOrUpdate(opinionsEntityInfo);
    	 
    	 // 判断保存是否成功失败
    	  if (ResultPojo.CODE_SUCCESS.equals(opinionsInfoJson.getString("code"))) {
    		  // 保存成功场合
    		  idMap.put("id", opinionsInfoJson.getJSONObject("result").getString("id"));
    		  resultInfo.setResult(idMap);
          } else {
        	 // 保存失败场合
        	  resultInfo.setCode(opinionsInfoJson.getString("code"));
        	  resultInfo.setMsg("[orgOpinionsService.saveOrUpdate] in function of orgInfoAudit "
        			  				+ ResultPojo.MSG_FAILURE  + "【"  + opinionsInfoJson.getString("msg") +"】");
        	  resultInfo.setResult(null);
         	  return resultInfo;
          }
    	  
    	  JSONObject statusEntityInfoDb =  orgStatusService.findById(baseId);
    	  JSONObject statusResult = null;
    	  // 判断取得状态信息是否成功
		  if (ResultPojo.CODE_SUCCESS.equals(statusEntityInfoDb.getString("code")) ) {
			  statusResult =  (JSONObject)statusEntityInfoDb.getJSONObject("result");  
		  } else {
			  // 取得失败场合
			  resultInfo.setCode(statusEntityInfoDb.getString("code"));
			  resultInfo.setMsg("[orgStatusService.findById] in function of orgInfoAudit " + ResultPojo.MSG_FAILURE + "【"  + statusEntityInfoDb.getString("msg") + "】" );
			  resultInfo.setResult(null);
		      // 程序事务控制
		  	  // TODO
			  return  resultInfo;
		  }
    	 //*******************第三步更新部门的状态表******************************************
		  statusEntityInfo.setOrgIntegrity(statusResult.getString("orgIntegrity"));
		  //设置变更变更强度
		  statusEntityInfo.setUpdateLevel(statusResult.getString("updateLevel"));
		 //设置变更子类型
		  statusEntityInfo.setChildType(statusResult.getString("childType"));
		  //设置变更原因
		  statusEntityInfo.setUpdateReason(statusResult.getString("updateReason"));
		  //设置是否是历史沿革
		  statusEntityInfo.setIsHistory(statusResult.getString("isHistory"));
		 // 设置UpdateType
		 statusEntityInfo.setUpdateType(statusResult.getString("updateType"));
    	 // 设置状态表ID
    	 statusEntityInfo.setId(baseId.toString());
    	  // 设置登录用户ID
		 statusEntityInfo.setRegUserId(statusResult.getString("regUserId"));
		 // 设置更新用户ID
		 statusEntityInfo.setUpdateUserId(UserUtils.getCurrentUser().getId());
		  // 执行保存部门的状态表
		  JSONObject statusInfoJson = orgStatusService.saveOrUpdate(statusEntityInfo);
		 
		  // 判断保存是否成功失败
		  if (ResultPojo.CODE_SUCCESS.equals(statusInfoJson.getString("code")) ) {
			  // 保存成功场合
			  resultInfo.setCode(ResultPojo.CODE_SUCCESS);
			  resultInfo.setMsg(ResultPojo.MSG_SUCCESS);
		  } else {
			 // 保存失败场合
			  resultInfo.setCode(statusInfoJson.getString("code"));
			  resultInfo.setMsg("[orgStatusService.save] in function of orgInfoAudit " + ResultPojo.MSG_FAILURE + "【"  + statusInfoJson.getString("msg") + "】" );
			  resultInfo.setResult(null);
		      // 程序事务控制
		  	  // 删除保存的部门审核意见信息 TODO
			  return  resultInfo;
		  }
		  
		 //*******************第四步审核通过场合将baseID更新到部门库表中********************************
		 if(Contsants.OFS_AUDIT_THROUGH.equals(statusEntityInfo.getStatus())) {
			 String orgId = null;
			// 根据baseID取得部门库ID（主表ID）
			JSONObject   baseInfoJson =  organizationBaseService.findById(baseId);
			if (ResultPojo.CODE_SUCCESS.equals(baseInfoJson.getString("code")) ) {
				orgId = baseInfoJson.getJSONObject("result").getString("orgId");
			} else {
				// 部门基本信息取得失败场合
				resultInfo.setCode(baseInfoJson.getString("code"));
				resultInfo.setMsg("[organizationBaseService.findById] in function of orgInfoAudit " + ResultPojo.MSG_FAILURE + "【"  + baseInfoJson.getString("msg") + "】" );
				resultInfo.setResult(null);
				return  resultInfo;
			}
			
			OrganizationEntity orgEntity = new OrganizationEntity();
			 // 根据orgID取得部门库详细信息
			JSONObject orgInfoJson =  organizationService.findById(orgId);
			
			if (ResultPojo.CODE_SUCCESS.equals(orgInfoJson.getString("code")) ) {
				orgEntity = JSONObject.toJavaObject(orgInfoJson.getJSONObject("result"), OrganizationEntity.class);
				// 部门库信息取得成功场合
				orgEntity.setBaseId(baseId.toString());
				// **********************************审核通过时点将部门基本信息表中的数据同步更新到部门库中*****************
				// 部门名称更新
				orgEntity.setName(baseInfoJson.getJSONObject("result").getString("name"));
				// 主管部门更新
				orgEntity.setParentId(baseInfoJson.getJSONObject("result").getString("compId"));
				// 机构类型更新
				orgEntity.setType(baseInfoJson.getJSONObject("result").getString("type"));
				// 所属系统更新
				orgEntity.setOwnSys(baseInfoJson.getJSONObject("result").getString("ownSys"));
				// 部门库表状态更新
				if(Contsants.OFS_UPDATE_TYPE_MERGE.equals(statusEntityInfo.getUpdateType())) {
					orgEntity.setStatus(Contsants.OFS_ORGANIZATION_FLAG_CANCEL);
				} else {
					orgEntity.setStatus(Contsants.OFS_ORGANIZATION_FLAG_NORMAL);
				}
				// 是否主管部门更新
				orgEntity.setIsComp(baseInfoJson.getJSONObject("result").getString("isComp"));
//				// 是否有下设部门更新
//				JSONObject orgInfoJsonResult =   organizationService.findChildOrgs(orgId);
//				// 注意result包了两层
//				JSONArray orgInfoJsonList =   orgInfoJsonResult.getJSONArray("result");
//				JSONObject orgInfoJsonObj = null;
//				String hasChild = Contsants.OFS_ORGANIZATION_FLAG_HAS_NO_CHILD;
//				for (int i=0; i < orgInfoJsonList.size(); i ++) {
//					orgInfoJsonObj = orgInfoJsonList.getJSONObject(i);
//					if(Contsants.OFS_ORGANIZATION_FLAG_NORMAL.equals(orgInfoJsonObj.getString("status")) ||
//							Contsants.OFS_ORGANIZATION_FLAG_CANCEL.equals(orgInfoJsonObj.getString("status"))) {
//						hasChild = Contsants.OFS_ORGANIZATION_FLAG_HAS_CHILD;
//						break;
//					}
//				}
				orgEntity.setHasChild(Contsants.OFS_ORGANIZATION_FLAG_HAS_NO_CHILD);
				// 设置更新时间
				orgEntity.setUpdateTime(new Date());
				// 设置更新用户ID
				 if(StringUtils.isNotEmpty(UserUtils.getCurrentUser().getId())) {
					 orgEntity.setUpdateUserId(Integer.valueOf(UserUtils.getCurrentUser().getId()));
		 		 }
				// TODO 以下字段暂不同步更新
				// 所属系统更新（areaID、areaCode、isSecret、local_code）
				// 部门编码和sort是创建的时点和赋码时点就固定了
				
			} else {
				// 部门库信息取得失败场合
				resultInfo.setCode(orgInfoJson.getString("code"));
				resultInfo.setMsg("[service.findById(organization)] in function of orgInfoAudit " + ResultPojo.MSG_FAILURE + "【"  + orgInfoJson.getString("msg") + "】" );
				resultInfo.setResult(null);
				return  resultInfo;
			}
			
			// 当变更的部门为主管部门时并且该部门的所属系统发生变更，
			// 此时递归更新该主管部门的下设机构的部门库信息和下设机构的部门基本信息的所属系统字段
			int ret =common.compOrgUpdateOwnSys(organizationService,organizationBaseService,orgEntity,resultInfo);
			if(ret != 0) {
				return resultInfo;
			}
			
			JSONObject  orgInfoJsonObj = (JSONObject)JSONObject.toJSON(orgEntity);
			// 根据ID更新部门库的编码信息
			JSONObject organizationInfoJson = organizationService.saveOrUpdate(orgInfoJsonObj);
			
			// 判断更新是否成功失败
			if (ResultPojo.CODE_SUCCESS.equals(organizationInfoJson.getString("code")) ) {
				// 保存成功场合
				resultInfo.setCode(ResultPojo.CODE_SUCCESS);
				resultInfo.setMsg(ResultPojo.MSG_SUCCESS);
				idMap.put("id", organizationInfoJson.getJSONObject("result").getString("id"));
				idMap.put("baseId", organizationInfoJson.getJSONObject("result").getString("baseId"));
				resultInfo.setResult(idMap);
			} else {
				// 保存失败场合
				resultInfo.setCode(organizationInfoJson.getString("code"));
				resultInfo.setMsg("[service.update(organization)] in function of orgInfoAudit " + ResultPojo.MSG_FAILURE + "【"  + organizationInfoJson.getString("msg") + "】" );
				resultInfo.setResult(null);
				 // 程序事务控制
			  	 // 删除保存的部门审核意见信息 TODO
				return  resultInfo;
			}
		}
		
         // 成功保存部门信息表和部门状态表返回
         return  resultInfo;
    }
}
